package com.jic.data.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * 名    称：IPUtils
 * 功    能：
 * 创 建 人：K.K
 * 创建时间：2020/11/28 18:29
 * 修 改 人：
 * 修改时间：
 * 说    明：
 * 版 本 号：
 */
public class IPUtils {

    private static final String LOCAL_IP = "127.0.0.1";

    public static String getIP(HttpServletRequest request) {
        String IP = request.getHeader("X-Real-IP");
        if (IP == null || IP.length() == 0 || "unknow".equalsIgnoreCase(IP)) {
            IP = request.getHeader("x-forwarded-for");
        }
        if (IP == null || IP.length() == 0 || "unknow".equalsIgnoreCase(IP)) {
            IP = request.getRemoteAddr();
            // 0:0:0:0:0:0:0:1是IPv6的地址，相当于IPv4的127.0.0.1
            if ("0:0:0:0:0:0:0:1".equals(IP)) {
                IP = LOCAL_IP;
            }
        }
        if (IP == null || IP.length() == 0 || "unknow".equalsIgnoreCase(IP)) {
            IP = LOCAL_IP;
        }
        int pos = IP.indexOf(',');
        if (pos >= 0) {
            IP = IP.substring(0, pos);
        }
        return IP;
    }
}
